<?php
namespace App\Module\Admin\Service;

use App\Model\Child;
use App\Module\Admin\Request\Child\CreateRequest;
use App\Module\Admin\Request\Child\UpdateRequest;

class ChildService {

    public function search($cname,$pname,$mobile,$pagesize){
        $query = Child::query()->latest("child_id");

        if(!empty($cname)){
            $query->where('name','like','%'.$cname.'%');
        }
        if(!empty($pname)){
            $query->where('parent_name','like','%'.$pname.'%');
        }
        if(!empty($mobile)){
            $query->where('parent_mobile','like','%'.$mobile.'%');
        }

        return $query->paginate($pagesize);
    }

    public function create(CreateRequest $request){
        $model = new Child();
        $model->fill($request->all());
        return $model->save();
    }

    public function getById($id){
        return Child::query()->find($id);
    }

    public function update(UpdateRequest $request,$id){
        $model = Child::query()->findOrFail($id);
        $model->fill($request->all());
        return $model->save();
    }

    public function delete($id){
        return Child::destroy($id);
    }

    //父母列表
    public function parents($id){
        return Child::query()->findOrFail($id)->users;
    }

    //解绑父母
    public function unbind($cid,$uid){
        return Child::query()->findOrFail($cid)->users()->detach($uid);
    }
}